<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>购物车</title>
    <link href="${applicationScope.basePath}/css/bootstrap.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="${applicationScope.basePath}/css/index.css">
    <script src="${applicationScope.basePath}/js/jquery-3.4.1.min.js"></script>
    <script src="${applicationScope.basePath}/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="${applicationScope.basePath}/css/model.css">
    <style>
        .table th, .table td {
            text-align: center;
            vertical-align: middle !important;
        }

        .cp {
            WORD-WRAP: break-word;
            TABLE-LAYOUT: fixed;
            word-break: break-all;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 4;
            overflow: hidden;
        }
    </style>
</head>
<body>
<jsp:include page="../header.jsp" flush="true"/>
<div class="container wow slideInDown" style="padding-top:80px;">
    <hr/>
    <div style="background-color: white;">
        <div class="panel-body">
            <div class="bs-example" data-example-id="table table-striped">
                <table class="table table-condensed">
                    <thead>
                    <tr style="background-color: #ff9900;">
                        <th style="width: 10%;text-align: left;"><input id="selectedAll" type="checkbox"/>全选</th>
                        <th style="text-align: left;width: 30%;">商品信息</th>
                        <th style="width: 10%;">单价</th>
                        <th style="width: 20%;">数量</th>
                        <th style="width: 10%;">金额</th>
                        <th style="width: 10%;">日期</th>
                        <th style="width: 30%;">操作</th>
                    </tr>
                    </thead>
                    <tbody id="content">
                    <c:if test="${!empty requestScope.cart}">
                        <c:forEach items="${requestScope.cart}" var="item" varStatus="vs">
                            <input id="ids_${vs.count}" type="hidden" value="${item.goodsExtend.goods.id}"/>
                            <tr id="row_${vs.count}">
                                <td class="tb1_td1" style="width: 10%;text-align: left;"><input
                                        onchange="setGP(this,${vs.count});"
                                        name="ids" type="checkbox"/>
                                </td>
                                <td style="width: 30%;">
                                    <div class="row">
                                        <div class="col-md-3">
                                            <a href="${applicationScope.basePath}/goods/detail/${item.goodsExtend.goods.id}"
                                               class="" title="点击查看详情">
                                                <img style="width: 110px;height: 70px;" class='img-rounded'
                                                     src="${applicationScope.imgPath}/${item.goodsExtend.imageList[0].imgUrl}"
                                                     alt="...">
                                            </a>
                                        </div>
                                        <div class="col-md-7" style="font-size:13px;color:#888888;margin-left: 40px;">
                                            <c:if test="${item.goodsExtend.goods.number > 0}">
                                                <p class="cp">${item.goodsExtend.goods.describle}</p>
                                            </c:if>
                                            <c:if test="${item.goodsExtend.goods.number <= 0}">
                                                <p style="font-size: 18px;color: red;font-weight: bold;">该商品暂无余货</p>
                                            </c:if>
                                        </div>
                                    </div>
                                </td>
                                <td style="font-weight: bold;width: 10%;">￥${item.goodsExtend.goods.price}</td>
                                <td style="width: 20%;">
                                    <div class="row">
                                        <c:if test="${item.goodsExtend.goods.number == 1}">
                                            <button type="button" class="btn btn-success disabled"
                                                    onclick="reduceNum(this,${vs.count},${item.goodsExtend.goods.number});">
                                                -
                                            </button>
                                            <a id="a_${vs.count}" type="button" class="btn btn-default" disabled>1</a>
                                            <button type="button" class="btn btn-success disabled"
                                                    onclick="addNum(this,${vs.count},${item.goodsExtend.goods.number});">
                                                +
                                            </button>
                                        </c:if>
                                        <c:if test="${item.goodsExtend.goods.number != 1}">
                                            <button type="button" class="btn btn-success"
                                                    onclick="reduceNum(this,${vs.count},${item.goodsExtend.goods.number});">
                                                -
                                            </button>
                                            <a id="a_${vs.count}" type="button" class="btn btn-default" disabled>1</a>
                                            <button type="button" class="btn btn-success"
                                                    onclick="addNum(this,${vs.count},${item.goodsExtend.goods.number});">
                                                +
                                            </button>
                                        </c:if>
                                    </div>
                                </td>
                                <td style="color: #db5e5e;font-weight: bold;width: 10%;">
                                    ￥${item.goodsExtend.goods.price}</td>
                                <td style="width: 10%">${item.start_at}</td>
                                <td style="width: 30%;">
                                    <a onclick="return removeCartItem(this,${vs.count},${item.goodsExtend.goods.id});"
                                       href="${applicationScope.basePath}/shopcart/remove"
                                       class="">删除</a>
                                    <br/>
                                    <a onclick="return collection(${item.goodsExtend.goods.id});" href="#"
                                       class="">加入收藏</a>
                                </td>
                            </tr>
                        </c:forEach>
                    </c:if>
                    </tbody>
                </table>
                <c:if test="${empty requestScope.cart}">
                    <p style="text-align: center;font-size: 18px;color: red;font-weight: bold;">购物车是空的，买点东西犒赏自己吧</p>
                </c:if>
            </div>
        </div>
    </div>
    <!--   -->
    <table class="table table-condensed">
        <tr style="background-color: #b6b4b9;">
            <td class="tb1_td1">
                <button id="clear_btn" class="btn btn-danger" type="button">清空购物车</button>
            </td>
            <td class="tb3_td2">已选商品<span id="selectGoodsNum" style="color: red;">0</span>件</td>
            <td class="tb3_td3">合计:￥<span id="totalPrice" style="color: red;">0</span></td>
            <td class="tb3_td4">
                <a href="#" id="settlement_btn" class="btn btn-info"
                   type="button">结算
                </a>
            </td>
        </tr>
    </table>
</div>
<footer>
    <hr/>
    <p style="text-align: center;">&copy; 二手交易平台 2020</p>
</footer>
<script type="text/javascript">
    $(function () {
        /*结算*/
        $("#settlement_btn").on('click', function () {
            //获取下边列表中的所有的checkbox
            const checkboxes = document.getElementsByName("ids");
            if (checkboxes.length > 0) {
                let id = '';
                let number = '';
                let goodsList = [];
                let json = {};
                // 遍历
                for (let i = 1; i <= checkboxes.length; i++) {
                    if (checkboxes[i - 1].checked === true) {
                        number = $("#a_" + i).text();
                        id = $("#ids_" + i).val();
                        json = {'id': id, 'number': number};
                        goodsList.push(json);
                    }
                }
                if (goodsList.length > 0) {
                    $.ajax({
                        url: '${applicationScope.basePath}/orders/msg',
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json;charset=UTF-8",
                        data: JSON.stringify(goodsList),
                        success: function (data) {
                            if (data.flag) {
                                window.location.href = '${applicationScope.basePath}/orders/myorders';
                            } else {
                                alert(data.errorMsg);
                            }
                        },
                        error: function () {
                        }
                    });
                } else {
                    alert("请选择至少一件商品");
                }
            } else {
                alert("购物车为空，无法结算");
            }
            return false;
        });

        /*全选*/
        $("#selectedAll").on("click", function () {
            //获取下边列表中的所有的checkbox
            const checkboxes = document.getElementsByName("ids");
            if ($(this).is(':checked')) {
                //遍历
                for (let i = 0; i < checkboxes.length; i++) {
                    //设置这些checkbox的选中状态
                    checkboxes[i].checked = this.checked;
                }
                let str = '';
                let num = 0;
                let totalPrice = 0;
                let str2 = '';
                // 设置结算清单
                for (let i = 1; i <= $("#content tr").length; i++) {
                    str = "#row_" + i + " div a";
                    num = num + parseInt($(str).text());
                    str2 = $($("#row_" + i).children()[4]).text();
                    totalPrice = totalPrice + parseInt(str2.substring(str2.lastIndexOf("￥") + 1));
                }
                $("#selectGoodsNum").text(num);
                $("#totalPrice").text(totalPrice);
            } else {
                //遍历
                for (let i = 0; i < checkboxes.length; i++) {
                    //设置这些checkbox的选中状态
                    checkboxes[i].checked = false;
                }
                $("#selectGoodsNum").text('0');
                $("#totalPrice").text('0');
            }
        });
        /*清空购物车*/
        $("#clear_btn").on("click", function () {
            const checkboxes = document.getElementsByName("ids");
            if (checkboxes.length > 0) {
                if (confirm("确定清空购物车吗？")) {
                    $.ajax({
                        url: '${applicationScope.basePath}/shopcart/empty',
                        type: "GET",
                        dataType: "json",
                        contentType: "application/json;charset=UTF-8",
                        success: function (data) {
                            if (data.flag) {
                                $("#content").empty();
                                $("#selectGoodsNum").text('0');
                                $("#totalPrice").text('0');
                                $("#cart_num").text('0');
                            } else {
                                alert("删除失败，请稍后重试");
                            }
                        },
                    });
                }
            } else {
                alert("购物车为空");
            }
        });
    });

    /*收藏*/
    function collection(id) {
        $.ajax({
            url: '${applicationScope.basePath}/user/collection/' + id,
            type: 'POST',
            dataType: 'json',
            success: function (data) {
                if (data.flag) {
                    alert("收藏成功！");
                } else {
                    alert(data.errorMsg);
                }
            },
            error: function () {
                alert('请求超时或系统出错!');
            }
        });
        return false;
    }

    /*将商品移出购物车*/
    function removeCartItem(obj, i, id) {
        let url = obj.href;
        let data = JSON.stringify({'id': id});
        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            contentType: "application/json;charset=UTF-8",
            data: data,
            success: function (data) {
                if (data.flag) {
                    $('#row_' + i).remove();
                    $("#cart_num").text(parseInt($("#cart_num").text()) - 1);
                } else {
                    alert("删除失败，请稍后重试");
                }
            },
        });
        return false;
    }

    /**
     * 单选
     */
    function setGP(obj, i) {
        let str = "#row_" + i + " div a";
        let num = parseInt($(str).text());
        let str2 = $($("#row_" + i).children()[4]).text();
        let totalPrice = parseInt(str2.substring(str2.lastIndexOf("￥") + 1));
        let allNum = parseInt($("#selectGoodsNum").text());
        let allPrice = parseInt($("#totalPrice").text());
        if ($(obj).is(':checked')) {
            $("#selectGoodsNum").text(allNum + num);
            $("#totalPrice").text(allPrice + totalPrice);
        } else {
            $("#selectGoodsNum").text(allNum - num);
            $("#totalPrice").text(allPrice - totalPrice);
        }
    }

    /**
     * 商品数量增加
     */
    function addNum(obj, i, size) {
        let num = parseInt($(obj).prev().text());
        let str1 = $($("#row_" + i).children()[2]).text();
        let str2 = $($("#row_" + i).children()[4]).text();
        let singlePrice = parseInt(str1.substring(str1.lastIndexOf("￥") + 1));
        let totalPrice = parseInt(str2.substring(str2.lastIndexOf("￥") + 1));
        if (num < size) {
            $(obj).prev().text(num + 1);
            num = parseInt($(obj).prev().text());
            if (num === size) {
                $(obj).attr("disabled", true);
            }
            if (num > 1) {
                $(obj).prev().prev().attr("disabled", false);
            }
            $($("#row_" + i).children()[4]).text("￥" + (totalPrice + singlePrice));
        }

    }

    /**
     * 商品数量减少
     */
    function reduceNum(obj, i, size) {
        let num = parseInt($(obj).next().text());
        let str1 = $($("#row_" + i).children()[2]).text();
        let str2 = $($("#row_" + i).children()[4]).text();
        let singlePrice = parseInt(str1.substring(str1.lastIndexOf("￥") + 1));
        let totalPrice = parseInt(str2.substring(str2.lastIndexOf("￥") + 1));
        if (num > 1) {
            $(obj).next().text(num - 1);
            num = parseInt($(obj).next().text());
            if (num === 1) {
                $(obj).attr("disabled", true);
            }
            if (num < size) {
                $(obj).next().next().attr("disabled", false);
            }
            $($("#row_" + i).children()[4]).text("￥" + (totalPrice - singlePrice));
        }
    }
</script>
</body>
</html>
